﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lyh.Core.Catcher;
using Lyh.Core.Domain;
using Lyh.Core.Storage;
using NHibernate;
using NHibernate.Criterion;

namespace Lyh.Core.Data
{
    public class BaseRepository<T> : IBaseRepository<T> where T : Entity
    {
        protected virtual ISession Session
        {
            get { return SessionBuilder.CreateSession(); }
        }

        public virtual T Load(string id)
        {
            try
            {
                var t = Session.Load<T>(id);
                return t;
            }
            catch (Exception ex)
            {
                throw new RepositoryException("加载实体失败", ex);
            }
        }

        public virtual T Get(string id)
        {
            try
            {
                var t = Session.Get<T>(id);
                return t;
            }
            catch (Exception ex)
            {
                throw new RepositoryException("获取实体失败", ex);
            }
        }

        public virtual IList<T> GetAll()
        {
            try
            {
                var lst = Session.CreateCriteria<T>().AddOrder(Order.Desc("CreateTime")).List<T>();
                return lst;
            }
            catch (Exception ex)
            {
                throw new RepositoryException("获取所有实体失败", ex);
            }
        }

        public virtual void SaveOrUpdate(T entity)
        {
            try
            {
                Session.SaveOrUpdate(entity);
                Session.Flush();
            }
            catch (Exception ex)
            {
                throw new RepositoryException("保存或更新实体失败", ex);
            }
        }

        public virtual void Update(T entity)
        {
            try
            {
                Session.Update(entity);
                Session.Flush();
            }
            catch (Exception ex)
            {
                throw new RepositoryException("更新实体失败", ex);
            }
        }

        public virtual void Delete(string id)
        {
            try
            {
                var t = Get(id);
                t.IsDeleted = true;
                Update(t);
            }
            catch (Exception ex)
            {
                throw new RepositoryException("逻辑删除实体失败", ex);
            }
        }

        public virtual void PhysicsDelete(string id)
        {
            try
            {
                var t = Get(id);
                Session.Delete(t);
                Session.Flush();
            }
            catch (Exception ex)
            {
                throw new RepositoryException("物理删除实体失败", ex);
            }
        }
    }
}
